package com.qdxwx.data.service.user;

import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.mapper.user.UserTokenMapper;
import com.qdxwx.models.user.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Service
public class UserTokenServiceImpl implements UserTokenService {

    @Autowired
    UserTokenMapper userTokenMapper;

    @Override
    public UserToken getByToken(String token) {
        return userTokenMapper.selectByToken(token);
    }

    @Override
    public UserToken get(long userId) {
        return userTokenMapper.selectByUserId(userId);
    }

    @Override
    public UserToken create(long userId) {
        UserToken token = new UserToken();
        token.setUserId(userId);
        token.setToken(TKConvert.toEncryptString(UUID.randomUUID().toString() + userId, "SHA"));
        if (save(token) < 1) {
            throw new RuntimeException("user token not created!");
        }
        return token;
    }

    @Override
    public int save(UserToken token) {
        if (token.getUserId() < 1 || token.getToken() == null) {
            return 0;
        }
        token.setUpdateTime(LocalDateTime.now());
        if (get(token.getUserId()) == null) {
            return userTokenMapper.insert(token);
        } else {
            return userTokenMapper.update(token);
        }
    }

    @Override
    public int delete(long userId) {
        return userTokenMapper.delete(userId);
    }
}
